<template>
  <div style="margin: 20px">
    <h2 style="text-align: center">注册</h2>
    <el-form
      id="form"
      label-position="right"
      label-width="100px"
      :model="formLabelAlign"
      style="max-width: 300px"
      ref="formRefs"
      :rules="formRules"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="formLabelAlign.account" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formLabelAlign.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">注册</el-button>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { reactive, ref } from "vue";
  import router from "@/router/index.js";
  import { ElMessage } from "element-plus";
  // const labelPosition = ref("right");

  // 登录数据表单
  const formLabelAlign = reactive({
    account: "",
    password: "",
  });

  // 登录验证规则
  const formRules = {
    account: [
      { required: true, message: "请输入账号", trigger: "blur" },
      {
        min: 3,
        max: 20,
        message: "账号长度在 3 到 20 个字符",
        trigger: "blur",
      },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      {
        min: 6,
        max: 20,
        message: "密码长度在 6 到 20 个字符",
        trigger: "blur",
      },
    ],
  };

  const formRefs = ref();
  // 登录跳转
  const login = () => {
    router.push({ path: "/login" });
  };
  const handleSubmit = () => {
    // 数据验证
    formRefs.value.validate((valid) => {
      // 表单验证通过逻辑
      if (valid) {
        // 判断LocalStorage是否存在账号密码
        if (localStorage.getItem("user")) {
          // localStorage存在 user 注册逻辑
          // 获取LocalStorage中的账号密码
          const user = JSON.parse(localStorage.getItem("user"));

          // 循环user，判断账号是否存在
          for (let i = 0; i < user.length; i++) {
            // 账号存在，提示账号已存在
            if (user[i].account === formLabelAlign.account) {
              ElMessage.error("账号已存在");
              return;
            }
          }
          // 账号不存在，将账号密码存入LocalStorage
          // 将账号密码存入LocalStorage
          user.push({
            account: formLabelAlign.account,
            pwd: formLabelAlign.password,
          });
          localStorage.setItem("user", JSON.stringify(user));
          ElMessage.success("注册成功！");
          return;
        }

        // localStorage不存在 user 注册逻辑
        //将账号密码存入LocalStorage
        const user = [
          { account: formLabelAlign.account, pwd: formLabelAlign.password },
        ];
        localStorage.setItem("user", JSON.stringify(user));
        ElMessage.success("注册成功！");
        login();
      } else {
        ElMessage.error("请检查输入内容正确性");
        return;
      }
    });
    // 处理登录逻辑
    console.log(formLabelAlign);
  };
</script>
